<template>
  <section class="comment-container">
    <comment-input
      :target-type="'article'"
      :target-id="articleId"
      @newArticleComment="refresh"
    />
    <ul class="comment-list">
      <comment-item
        v-for="item of commentList"
        :key="item.id"
        :comment="item"
        :article-comment-id="item.id"
        :focusid="focusId"
        @newReplyComment="refresh"
        @updateFocus="updateFocus"
      />
    </ul>
    <div
      v-loading="loading"
      class="more-loading"
    >
      <div
        v-show="btn_more"
        class="more"
        @click="getCommentList({ more: true })"
      >
        加载更多
      </div>
    </div>
  </section>
</template>

<script>
import CommentItem from '~/components/comment/CommentItem'
import CommentInput from '~/components/comment/CommentInput'

export default {
  name: 'Comment',
  components: {
    CommentItem,
    CommentInput
  },
  props: {
    articleId: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      focusId: '',
      commentList: [],
      pagination: 1,
      loading: false,
      btn_more: true
    }
  },
  computed: {
    userData() {
      return this.$store.state.user.userData
    }
  },
  watch: {
    articleId(newVal) {
      if (newVal) {
        this.getCommentList()
      }
    }
  },
  methods: {
    async getCommentList({
      type = 'new',
      pageNum = this.pagination,
      pageSize = 6,
      more = false
    } = {}) {
      this.loading = true
      this.btn_more = false
      const params = {
        articleId: this.articleId,
        pageNum,
        pageSize,
        type,
        userId: this.userData ? this.userData.userId : ''
      }
      let data = await this.$request({
        context: this,
        method: 'post',
        url: `articleComment/list`,
        params
      })
      this.loading = false
      if (!data) return
      data = data.commentList
      if (data.length === 0) {
        this.$message.success('没有评论啦')
        if (!more) {
          this.commentList = []
        }
        return
      }
      if (data.length === pageSize) {
        this.btn_more = true
      }
      this.pagination++
      if (more) {
        this.commentList = [...this.commentList, ...data]
      } else {
        this.commentList = data
      }
    },
    refresh() {
      this.focusId = ''
      this.pagination = 1
      this.getCommentList()
    },
    updateFocus(id) {
      this.focusId = id.toString()
    }
  }
}
</script>

<style scoped lang="scss">
  @import "~@/assets/css/public";
  .comment-container {
    box-sizing: border-box;
    border: 1px solid $theme-color-border;
    background: #fff;
    padding: 18px 24px 46px;
    margin: 10px auto 242px;
  }
</style>
